<div class="box fullwidth">
<?php
	// Show list
	if(!isset($_GET['product']))
	{
		$pr = $db->query("SELECT * FROM produkter ORDER BY namn ASC");
		foreach($pr as $p)
		{
			//$p->namn = htmlspecialchars(iconv("","UTF-8", $p->namn));
			//$p->beskrivning = htmlspecialchars(iconv("","UTF-8", $p->beskrivning));
			//$db->update("UPDATE produkter SET namn='$p->namn', beskrivning='$p->beskrivning' WHERE id='$p->id'");
			
			print "<a href='?page=edit_product&product=".$p->id."' style='display:inline-block;padding:5px;'>&raquo; ".$p->namn."</a><br/>";
		}
	}
	
	if(isset($_POST['save']))
	{
		$id = mysql_real_escape_string($_POST['id']);
		$url = mysql_real_escape_string($_POST['imgurl']);
		
		$db->update("UPDATE produkter SET bildurl ='$url' WHERE id='$id'");
		
		header("Location: ?page=edit_product", true);
	}
	
	if(isset($_GET['product']))
	{
		$id = intval(stripslashes($_GET['product']));
		$p = $db->query("SELECT * FROM produkter WHERE id='$id'");
		
		?>
        <a href="?page=edit_product">&laquo; LISTAN</a>
        <hr />
        <form method="post" action="">
        	<input type="hidden" name="id" value="<?=$p->id;?>"/>
            <input id="thefield" type="text" name="imgurl" value="<?=$p->bildurl;?>" style="padding:4px; width:300px; opacity:.7;"> Ange en bild för produkten <strong><?=$p->namn;?></strong> genom att klicka på en bild nedan!<br>
            <input type="submit" value="Spara" name="save" />
            <center> <img id='theimage' src="<?=$p->bildurl;?>" style="width:250px; height:auto;" /><br></center>
            <hr/>
            <?php
				//Open images directory
				$folder = "images/products/";
				$dir = dir($folder);
				
				//List files in images directory
				while (($file = $dir->read()) !== false)
				{
					if($file!=="." && $file!== "..")
					{
						$url = $folder.$file;
						echo "<a onclick='assignImage(\"".$url."\");' class='product_preview'><img src='$url'/><span>".$file."</span></a>";
					}
				}
				
				$dir->close();
			
			?>
        </form>
        <script language="javascript" type="text/javascript">
			function assignImage(url)
			{
				$("#theimage").attr("src", url);
				$("#thefield").val(url);
			}
		</script>
		<?
	}
	
?>
</div>